package com.khyr.service.impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.khyr.dao.DeptDao;
import com.khyr.dao.SchedulingDao;
import com.khyr.entity.Dept;
import com.khyr.entity.HisPatient;
import com.khyr.entity.Scheduling;
import com.khyr.entity.User;
import com.khyr.feign.UserFeign;
import com.khyr.service.SchedulingService;
import com.khyr.vo.R;
import com.khyr.vo.SaveSchedulingVo;
import com.khyr.vo.SchedulingDto;
import com.khyr.vo.SchedulingVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class SchedulingServiceImpl implements SchedulingService {
    @Autowired
    private SchedulingDao schedulingDao;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private DeptDao deptDao;
    /**
     * @create by: Zr
     * @description: 根据条件查询值班医生，调用了services-system中的getSchedulingDoctorByCon
     * @create time: 2025/3/14 11:38
     * @param vo
     * @return com.khyr.vo.R<java.util.Map<java.lang.String,java.lang.Object>>
     */
    @Override
    public R<Map<String,Object>> docterScheduling(SchedulingVo vo) {
        //1. 按照条件查询值班医生的信息。
        Map<String,Object> map=new HashMap<>();
        map.put("deptId",vo.getDeptId());
        map.put("userId",vo.getUserId());
        R<List<User>> schedulingDoctorByCon = userFeign.getSchedulingDoctorByCon(map);
        List<User> user = schedulingDoctorByCon.getData();
        return getResult(vo,user);
    }
    /**
     * @create by: Zr
     * @description: 查询所有可用科室的信息
     * @create time: 2025/3/13 14:36
     * @param
     * @return com.khyr.vo.R<java.util.List<com.khyr.entity.Dept>>
     */
    @Override
    public R<List<Dept>> getDeptList() {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        // 未删除的
        queryWrapper.eq("del_flag","0");
        // 未停用的
        queryWrapper.eq("status","0");
        List<Dept> deptList = deptDao.selectList(queryWrapper);
        return new R<>(200,"查询成功",deptList);
    }
    /**
     * @create by: Zr
     * @description: 根据前端传入的数据，根据日期和userId删除排班，再重新添加排班
     * @create time: 2025/3/13 15:46
     * @param vo
     * @return com.khyr.vo.R<java.lang.String>
     */
    @Override
    public R<String> saveScheduling(SaveSchedulingVo vo,String name) {
        // 将字符串转换为Date对象
        Date startDate = DateUtil.parse(removeParenthesesAndContent(vo.getBeginDate()), "yyyy-MM-dd");
        // 获取该周的结束日期（周日）
        Date endDate = DateUtil.endOfWeek(startDate);

        // 构建查询条件并删除现有排班记录
        QueryWrapper<Scheduling> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", vo.getData().get(0).getUserId());
        wrapper.between("scheduling_day", DateUtil.format(startDate, "yyyy-MM-dd"), DateUtil.format(endDate, "yyyy-MM-dd"));
        schedulingDao.delete(wrapper);

        Integer userId = vo.getData().get(0).getUserId();
        Integer deptId = vo.getData().get(0).getDeptId();

        System.out.println("用户id" + userId);
        System.out.println("开始时间" + startDate + " 结束日期" + endDate);

        // 遍历每一天并保存排班记录
        for (int i = 0; i < 7; i++) {
            Date day = DateUtil.offsetDay(startDate, i);
            String dayStr = DateUtil.format(day, "yyyy-MM-dd");

            for (SchedulingDto dto : vo.getData()) {
                int subsectionType = dto.getSubsectionType();
                List<String> schedulingType = new ArrayList<>(dto.getSchedulingType());

                if (i < schedulingType.size() && schedulingType.get(i) != "") {
                    Scheduling scheduling = new Scheduling();
                    scheduling.setUserId(userId);
                    scheduling.setDeptId(deptId);
                    scheduling.setSchedulingDay(dayStr);
                    scheduling.setSubsectionType(String.valueOf(subsectionType));
                    scheduling.setSchedulingType(String.valueOf(schedulingType.get(i)));
                    scheduling.setCreateTime(new Date());
                    scheduling.setCreateBy(name);
                    schedulingDao.insert(scheduling);
                }
            }
        }

        return new R<>(200, "保存成功", "");
    }
    private String removeParenthesesAndContent(String input) {
        // 使用正则表达式去除括号及其内部的内容
        return input.replaceAll("\\(.*?\\)", "");
    }

    private R<Map<String,Object>> getResult(SchedulingVo vo, List<User> users) {
        //1.判断是否传递查询的日期
        Date date=new Date();//当前时间
        if(vo.getQueryDate()!=null){ //2025-03-16  hutool工具
             //判断传递的日期是否为周日 parse(String,格式) 把指定得到字符串转成相应的日期格式
            DateTime parse = DateUtil.parse(vo.getQueryDate(), "yyyy-MM-dd");
            int i = DateUtil.dayOfWeek(parse);
            if(i==1){//表示周日
                date=DateUtil.offsetDay(parse,1);
            }else{
                date=DateUtil.offsetDay(parse,-1);
            }
        }
        //2.获取日期的这周的开始日期和结束日期
        Date beginDate = DateUtil.beginOfWeek(date);
        Date endDate = DateUtil.endOfWeek(date);
        vo.setBeginDate(DateUtil.format(beginDate,"yyyy-MM-dd"));
        vo.setEndDate(DateUtil.format(endDate,"yyyy-MM-dd"));
        //3.查询值班记录表
        List<Scheduling> schedulingDtos = getScheduling(vo);
        //4.封装到dto中
        List<SchedulingDto> schedulingDtoList = new ArrayList<>();
        for(User user:users){
            //表示上午值班
            SchedulingDto schedulingDto1 = new SchedulingDto(Integer.valueOf(user.getUserId()+""),Integer.valueOf(user.getDeptId()+""),1,
                    initMap(beginDate));
            //表示下午值班
            SchedulingDto schedulingDto2 = new SchedulingDto(Integer.valueOf(user.getUserId()+""),Integer.valueOf(user.getDeptId()+""),2,initMap(beginDate));
            //表示晚上值班
            SchedulingDto schedulingDto3 = new SchedulingDto(Integer.valueOf(user.getUserId()+""),Integer.valueOf(user.getDeptId()+""),3,initMap(beginDate));
            for (Scheduling scheduling:schedulingDtos){
                String subsectionType = scheduling.getSubsectionType();//值班时间段
                String schedulingType = scheduling.getSchedulingType();//值班类型
                Integer userId = scheduling.getUserId();//值班医生
                if((userId+"").equals(user.getUserId()+"")){
                    switch (subsectionType){
                        case "1":
                            schedulingDto1.getMap().put(scheduling.getSchedulingDay(),schedulingType);
                            break;
                        case "2":
                            schedulingDto2.getMap().put(scheduling.getSchedulingDay(),schedulingType);
                            break;
                        case "3":
                            schedulingDto3.getMap().put(scheduling.getSchedulingDay(),schedulingType);
                            break;
                        default:
                            break;
                    }
                }
            }

            schedulingDto1.setSchedulingType(schedulingDto1.getMap().values());
            schedulingDto2.setSchedulingType(schedulingDto2.getMap().values());
            schedulingDto3.setSchedulingType(schedulingDto3.getMap().values());
            schedulingDtoList.add(schedulingDto1);
            schedulingDtoList.add(schedulingDto2);
            schedulingDtoList.add(schedulingDto3);

        }


        Map<String,Object> result=new HashMap<>();
        result.put("tableData",schedulingDtoList); //值班的表格数据
        result.put("beginDate",DateUtil.format(beginDate,"yyyy-MM-dd")+"(周一)");
        result.put("endDate",DateUtil.format(endDate,"yyyy-MM-dd")+"(周日)");
        result.put("labelNames",getLabeld(beginDate));

        return new R<>(200,"查询成功",result);
    }

    private List<String> getLabeld(Date beginDate) {
         List<String> weeks=new ArrayList<>();
         for(int i=0;i<7;i++){
             Date date = DateUtil.offsetDay(beginDate, i);
             String format = DateUtil.format(date, "yyyy-MM-dd")+getWeek(i);
             weeks.add(format);
         }
         return weeks;
    }

    private String getWeek(int i) {
        switch (i){
            case 0:
                return "(周一)";
            case 1:
                return "(周二)";
            case 2:
                return "(周三)";
            case 3:
                return "(周四)";
            case 4:
                return "(周五)";
            case 5:
                return "(周六)";
            case 6:
                return "(周日)";
        }
        return null;
    }

    //初始化这周的值班情况
    private Map<String, String> initMap(Date beginDate) {
        Map<String,String> map=new LinkedHashMap<>();//有序
        for(int i=0;i<7;i++){
            Date date = DateUtil.offsetDay(beginDate, i);
            String format = DateUtil.format(date, "yyyy-MM-dd");
            map.put(format,"");
        }
        return map;
    }

    private List<Scheduling> getScheduling(SchedulingVo vo) {
        QueryWrapper<Scheduling> wrapper=new QueryWrapper<>();
        if(vo.getUserId()!=null){
            wrapper.eq("user_id",vo.getUserId());
        }
        if(vo.getDeptId()!=null){
            wrapper.eq("dept_id",vo.getDeptId());
        }
        if(vo.getBeginDate()!=null&&vo.getEndDate()!=null){
            wrapper.between("scheduling_day",vo.getBeginDate(),vo.getEndDate());
        }
        return schedulingDao.selectList(wrapper);
    }
}











